
declare namespace g = "ddi:group:3_1";
declare namespace dc="ddi:dcelements:3_1";
declare namespace d="ddi:datacollection:3_1"; 
declare namespace dc2="http://purl.org/dc/elements/1.1/"; 
declare namespace s="ddi:studyunit:3_1"; 
declare namespace c="ddi:conceptualcomponent:3_1";
declare namespace r="ddi:reusable:3_1"; 
declare namespace a="ddi:archive:3_1"; 
declare namespace ddi="ddi:instance:3_1"; 
declare namespace l="ddi:logicalproduct:3_1";

import module namespace request="http://exist-db.org/xquery/request";
import module namespace json="http://www.json.org";

declare option exist:serialize "method=text media-type=application/json";

let $lang := request:get-parameter("lang", ("en"))

(: if callback is defined :)
let $callback := request:get-parameter("callback", ())

let $collection := '/db/ddi/data/ddi3/internal'

let $series := collection($collection)/ddi:DDIInstance/g:Group
let $output := <series-list>
                {
                for $s in $series
                  order by ($s/r:SeriesStatement/r:SeriesName[@xml:lang=$lang])
                        return <series>
                                    <id>{number($s/r:UserID)}</id>
                                    <url>{$collection}/{util:document-name($s)}</url>
                                    <name>{string($s/r:SeriesStatement/r:SeriesName[@xml:lang=$lang])}</name>
                                    {
                                            for $study_id in $s/g:StudyUnit/g:Reference/r:ID
                                                    return <study>{number($study_id)}</study>
                                    }
                                </series>
                }
                </series-list>
return 
	if(empty($callback))
	then
		json:xml-to-json($output)
	else
		($callback, "(", json:xml-to-json($output),")")
